import utils.FileUtils;
import utils.SystemLookup;

import java.math.BigInteger;
import java.util.Arrays;

public class BubbleSort {
    private static long elapsedNanoTime = 0;
    private static BigInteger elapsedTime = BigInteger.ZERO;

    public static void main(String[] args) {

        if (args.length < 2 || args.length > 11) {
            System.out.println("Nieprawidlowa liczba parametrów!");
        }

        int numberOfExec = 0;
        try {
            numberOfExec = Integer.parseInt(args[0]);
            System.out.println("Liczba powtórzeń sortowania: " + numberOfExec );
        } catch (Exception ex) {
            System.out.println("Niepopawne parsowanie pierwszego parametru");
            System.exit(1);
        }

        String[] fileNames = Arrays.copyOfRange(args, 1, args.length);
        System.out.println("Pliki: " + Arrays.toString(fileNames));

        for (String fileName : fileNames) {
            String[] out = FileUtils.readTextFileLine(SystemLookup.PATH_TO_LOAD + fileName + FileUtils.FILE_EXTENSION).split(" ");
            int[] arrayToSort = new int[out.length];
            System.out.println("Plik: " + fileName + "\tElementów: " + out.length);
            for (int i = 0; i < out.length; i++) {
                arrayToSort[i] = Integer.parseInt(out[i]);
            }

            for (int i = 0; i < numberOfExec; i++) {
                int[] intArray = Arrays.copyOf(arrayToSort, arrayToSort.length);
                long timeStart = System.nanoTime();
                bubbleSort(intArray);
                elapsedNanoTime = System.nanoTime() - timeStart;
                elapsedTime = elapsedTime.add(BigInteger.valueOf(elapsedNanoTime));
//                System.out.println(Arrays.toString(intArray));
            }
        }

        System.out.println("\nNano Time: " + elapsedTime.toString());
        System.out.println("Milliseconds Time: " + elapsedTime.divide(new BigInteger("1000000")));
        System.out.println("Seconds Time: " + elapsedTime.divide(new BigInteger("1000000000")));

    }

    public static void bubbleSort(int[] a) {
        int size = a.length - 1;
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = 0; j < size; j++) {
                if (a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
            size--;
        }
    }

    private static void bubbleSort2(int tab[]) {
        int temp;
        int zmiana = 1;
        while (zmiana > 0) {
            zmiana = 0;
            for (int i = 0; i < tab.length - 1; i++) {
                if (tab[i] > tab[i + 1]) {
                    temp = tab[i + 1];
                    tab[i + 1] = tab[i];
                    tab[i] = temp;
                    zmiana++;
                }
            }
        }
    }
}
